package com.boomsecret.juc.atomic;

import com.boomsecret.juc.atomic.AtomicReferenceFieldUpdaterDemo.Person.Address;

import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;

/**
 * @author wangjinliang on 2019/1/17.
 */
public class AtomicReferenceFieldUpdaterDemo {

    public static void main(String[] args) {
        AtomicReferenceFieldUpdater<Person, Address> addressAtomicReferenceFieldUpdater = AtomicReferenceFieldUpdater.newUpdater(Person.class, Address.class, "address");

        Address address01 = new Address("address01");
        Person person = new Person(address01);
        System.out.println(addressAtomicReferenceFieldUpdater.get(person));

        System.out.println("---------------------------");
        Address address02 = new Address("address02");
        addressAtomicReferenceFieldUpdater.compareAndSet(person, address01, address02);
        System.out.println(addressAtomicReferenceFieldUpdater.get(person));

        System.out.println("---------------------------");
        Address address03 = new Address("address03");
        addressAtomicReferenceFieldUpdater.weakCompareAndSet(person, address01, address03);
        System.out.println(addressAtomicReferenceFieldUpdater.get(person));
    }

    public static class Person {
        volatile Address address;

        public Person(Address address) {
            this.address = address;
        }

        public static class Address {
            private String address;

            public Address(String address) {
                this.address = address;
            }

            public String getAddress() {
                return address;
            }

            public void setAddress(String address) {
                this.address = address;
            }

            @Override
            public String toString() {
                return "Address{" +
                        "address='" + address + '\'' +
                        '}';
            }
        }
    }
}
